package com.sright.bcard.content.biz.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.sright.bcard.common.service.share.dto.common.CheckImageDTO;
import com.sright.bcard.common.service.share.dto.common.CheckResultDTO;
import com.sright.bcard.common.service.share.dto.request.TextCheckRequest;
import com.sright.bcard.common.service.share.enums.BucketTypeEnum;
import com.sright.bcard.common.service.share.enums.CardTypeEnum;
import com.sright.bcard.common.service.share.enums.MaterialTypeEnum;
import com.sright.bcard.common.service.share.enums.SourceTypeEnum;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.AliyunUitls;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.share.service.ContentCheckService;
import com.sright.bcard.content.biz.manager.CardSettingManager;
import com.sright.bcard.content.dal.dao.CardSettingDAO;
import com.sright.bcard.content.dal.dao.CardUserInfoDAO;
import com.sright.bcard.content.dal.dao.MaterialDAO;
import com.sright.bcard.content.dal.dao.UserDAO;
import com.sright.bcard.content.dal.entity.CardSettingDO;
import com.sright.bcard.content.dal.entity.CardUserInfoDO;
import com.sright.bcard.common.service.share.dto.content.CardSettingDTO;
import com.sright.bcard.content.dal.entity.MaterialDO;
import com.sright.bcard.content.dal.entity.UserDO;
import com.sright.bcard.content.share.request.ShareImageParamRequest;
import com.sright.bcard.content.share.service.TextCheckService;
import com.sright.bcard.user.dal.dao.MemberDAO;
import com.sright.bcard.user.dal.entity.MemberDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CardSettingManagerImpl implements CardSettingManager {

    @Autowired
    private CardSettingDAO cardSettingDAO;

    @Autowired
    private CardUserInfoDAO cardUserInfoDAO;

    @Autowired
    private MaterialDAO materialDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private ContentCheckService contentCheckService;

    @Autowired
    private TextCheckService textCheckService;

    @Override
    public CardSettingDTO getSetting(Long userId) {
        CardSettingDO cardSettingDO = cardSettingDAO.selectByUserId(userId);
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userId);
        CardSettingDTO cardSettingDTO;
        if (cardSettingDO == null) {
            cardSettingDTO = new CardSettingDTO();
            cardSettingDTO.setEnable1(0);
            cardSettingDTO.setEnable3(1);
            cardSettingDTO.setForwardTitle("我是" + cardUserInfoDO.getName() + "，邀请您与我交换CuFace名片");
            cardSettingDTO.setVisitorTitle("欢迎来访");
            cardSettingDTO.setNewVisitorPush(0);
            cardSettingDTO.setVisitorDataPush(0);
            cardSettingDTO.setShowMobile(0);
            cardSettingDTO.setImgType(0);
            cardSettingDTO.setFilePath("");
        } else {
            cardSettingDTO = DataConvertUtils.convertDO2DTO(cardSettingDO, CardSettingDTO.class);
            if (cardSettingDO.getMaterialId() > 0) {
                MaterialDO materialDO = materialDAO.selectById(cardSettingDO.getMaterialId());
                if (materialDO == null) {
                    cardSettingDTO.setFilePath("");
                } else {
                    cardSettingDTO.setFilePath(materialDO.getFilePath());
                }

            } else {
                cardSettingDTO.setFilePath("");
            }
        }

        if (cardSettingDO == null || StringUtils.isEmpty(cardSettingDO.getVisitorTitle())) {
            cardSettingDTO.setVisitorTitle("欢迎来访");
        }
        if (cardSettingDO == null || StringUtils.isEmpty(cardSettingDO.getForwardTitle())) {
            cardSettingDTO.setForwardTitle("我是" + cardUserInfoDO.getName() + "，邀请您与我交换CuFace名片");
        }
        return cardSettingDTO;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long setimg(ShareImageParamRequest shareImageParamRequest) {
        // 根据memberId查询user信息
        UserDO userDO = userDAO.selectById(shareImageParamRequest.getUserId());
        // 根据userId查询cartSetting
        CardSettingDO cardSettingDO = cardSettingDAO.selectByUserId(shareImageParamRequest.getUserId());

        Long materialId;
        int isCheck;
        CheckImageDTO checkImageDTO;
        if (shareImageParamRequest.getImgType() == 2) {
            //阿里云图片审核
             checkImageDTO = checkImage(shareImageParamRequest.getImg(),userDO.getId());
            isCheck = 1;
        } else {
            checkImageDTO = null;
            isCheck = 0;
        }

        // 查询material素材表
        MaterialDO materialDO = new MaterialDO();
        materialDO.setUserId(shareImageParamRequest.getUserId());
        List<MaterialDO> materialDOS = materialDAO.selectByExample(materialDO);
        if(CollectionUtils.isNotEmpty(materialDOS)) {
            List<MaterialDO> shareMaterialList = materialDOS.stream().filter
                    (data -> data.getType().intValue() == MaterialTypeEnum.SHARE_PICTURE.getValue()).collect(Collectors.toList());
            // 如果不存在分享图则新增
            if(CollectionUtils.isEmpty(shareMaterialList)) {
                // 构建material实体
                materialDO.setFilePath(shareImageParamRequest.getImg());
                materialDO.setCardType(CardTypeEnum.PERSONAL.getValue());
                materialDO.setType(MaterialTypeEnum.SHARE_PICTURE.getValue());
                if (checkImageDTO != null) {
                    materialDO.setNeedReview(checkImageDTO.getNeedReview());
                    materialDO.setCheckResult(checkImageDTO.getCheckResult());
                }
                materialDO.setIsCheck(isCheck);
                materialId = materialDAO.insertSelective(materialDO);
                // 否则就是修改
            } else {
                MaterialDO shareMaterialDO = shareMaterialList.get(0);
                shareMaterialDO.setFilePath(shareImageParamRequest.getImg());
                shareMaterialDO.setIsCheck(isCheck);
                if (checkImageDTO != null) {
                    shareMaterialDO.setNeedReview(checkImageDTO.getNeedReview());
                    shareMaterialDO.setCheckResult(checkImageDTO.getCheckResult());
                } else {
                    shareMaterialDO.setNeedReview(0);
                    shareMaterialDO.setCheckResult("");
                }
                materialDAO.updateSelective(shareMaterialDO);
                materialId = shareMaterialDO.getId();
            }
        } else {
            materialDO.setFilePath(shareImageParamRequest.getImg());
            materialDO.setCardType(CardTypeEnum.PERSONAL.getValue());
            materialDO.setType(MaterialTypeEnum.SHARE_PICTURE.getValue());
            materialDO.setIsCheck(isCheck);
            if (checkImageDTO != null) {
                materialDO.setNeedReview(checkImageDTO.getNeedReview());
                materialDO.setCheckResult(checkImageDTO.getCheckResult());
            }
            materialId = materialDAO.insertSelective(materialDO);

        }
        if(null == cardSettingDO) {
            CardSettingDO cardSetting = new CardSettingDO();
            cardSetting.setImgType(shareImageParamRequest.getImgType());
            cardSetting.setMaterialId(materialId);
            cardSetting.setUserId(shareImageParamRequest.getUserId());
            if (userDO.getEnterpriseId() > 0) {
                cardSetting.setEnterpriseId(userDO.getEnterpriseId());
            }
            cardSettingDAO.insertSelective(cardSetting);
        } else {
            // 更新分享图id到cardsetting
            cardSettingDO.setMaterialId(materialId);
            cardSettingDO.setImgType(shareImageParamRequest.getImgType());
            cardSettingDAO.updateSelective(cardSettingDO);
        }
        return materialId;
    }

    /**
     * 进行阿里云图片审核
     * @param filePath
     * @return
     */
    public CheckImageDTO checkImage(String filePath,Long userId) {
        CheckResultDTO checkResultDTO = contentCheckService.singleImageCheck(filePath,userId);
        if (checkResultDTO == null) {
            throw new BusinessErrorException(BusinessCode.IMAGE_CHECK_ERROR);
        }
        CheckImageDTO checkImageDTO = new CheckImageDTO();
        if (checkResultDTO.getAd().equals("block") || checkResultDTO.getPorn().equals("block") || checkResultDTO.getTerrorism().equals("block")) {
            AliyunUitls.deleteSingleFile(BucketTypeEnum.IMAGE.getValue(),filePath);
            throw new BusinessErrorException(BusinessCode.IMAGE_CONTAIN_SENSITIVE_INFO);
        } else {
            if (checkResultDTO.getAd().equals("review") || checkResultDTO.getPorn().equals("review") || checkResultDTO.getTerrorism().equals("review")) {
                checkImageDTO.setNeedReview(1);
            } else {
                checkImageDTO.setNeedReview(0);
            }
            checkImageDTO.setCheckResult(JSONObject.toJSONString(checkResultDTO));
            return checkImageDTO;
        }
    }

    @Override
    public Long userSetting(CardSettingDTO cardSettingDTO) {
        //新增敏感词审核
        TextCheckRequest request = new TextCheckRequest();
        request.setForwardTitle(cardSettingDTO.getForwardTitle());
        request.setVisitorTitle(cardSettingDTO.getVisitorTitle());
        request.setUserId(cardSettingDTO.getUserId());
        textCheckService.textCheck(request,cardSettingDTO.getMemberId(), SourceTypeEnum.APPLET.getValue());

        if (cardSettingDTO.getId() != null) {
            CardSettingDO cardSettingDO = cardSettingDAO.selectById(cardSettingDTO.getId());
            cardSettingDO.setEnable1(cardSettingDTO.getEnable1());
            cardSettingDO.setEnable3(cardSettingDTO.getEnable3());
            cardSettingDO.setForwardTitle(cardSettingDTO.getForwardTitle());
            cardSettingDO.setVisitorTitle(cardSettingDTO.getVisitorTitle());
            cardSettingDO.setVisitorDataPush(cardSettingDTO.getVisitorDataPush());
            cardSettingDO.setNewVisitorPush(cardSettingDTO.getNewVisitorPush());
            cardSettingDO.setShowMobile(cardSettingDTO.getShowMobile());
            cardSettingDAO.updateSelective(cardSettingDO);
            return cardSettingDTO.getId();
        } else {
            CardSettingDO cardSettingDO = new CardSettingDO();
            cardSettingDO.setEnable1(cardSettingDTO.getEnable1());
            cardSettingDO.setEnable3(cardSettingDTO.getEnable3());
            cardSettingDO.setForwardTitle(cardSettingDTO.getForwardTitle());
            cardSettingDO.setVisitorTitle(cardSettingDTO.getVisitorTitle());
            cardSettingDO.setVisitorDataPush(cardSettingDTO.getVisitorDataPush());
            cardSettingDO.setNewVisitorPush(cardSettingDTO.getNewVisitorPush());
            cardSettingDO.setShowMobile(cardSettingDTO.getShowMobile());
            cardSettingDO.setUserId(cardSettingDTO.getUserId());
            return cardSettingDAO.insertSelective(cardSettingDO);
        }
    }

    @Override
    public Boolean setMobile(String mobile, Long memberId) {
        MemberDO memberDO = memberDAO.selectById(memberId);
        memberDO.setMobile(mobile);
        return memberDAO.updateSelective(memberDO);
    }
}
